package com.wechat.service.quartz.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wechat.service.enties.JobPo;
import com.wechat.service.quartz.bo.InitJobBo;
import com.wechat.service.quartz.dao.IJobDao;



@Service
public class DefualtJobServiceImpl implements IJobService {
	private final static Logger log = LoggerFactory.getLogger(DefualtJobServiceImpl.class);
/*	@Autowired
	private JobMapper jobMapper;*/
	
	@Autowired
	private IJobDao jobDao;

	@Override
	public List<InitJobBo> getAllJob() {
		log.info("从数据库获取到一个List集合Job");
		List<JobPo> selectAll = jobDao.selectAll();
		ArrayList<InitJobBo> arrayList = new ArrayList<InitJobBo>();
		if(selectAll == null) {
			return arrayList;
		}
		for (JobPo jobPo : selectAll) {
			InitJobBo bo = new InitJobBo(jobPo.getTaskCron(), jobPo.getTaskName(), jobPo.getClassName(),
					jobPo.getTaskGroup(), jobPo.getTaskDesc(), jobPo.getTaskRun().booleanValue());
			arrayList.add(bo);
		}
		return arrayList;
	}

	@Transactional
	@Override
	public void saveAll(List<InitJobBo> bos) {
		List<JobPo> selectAll = jobDao.selectAll();
		log.info("保存完成" + bos);
		for (InitJobBo bo : bos) {
	/*		JobPo jobPo = JobPo.builder().className(bo.getClassName()).createTime(new Date()).taskCron(bo.getTaskCron())
					.taskDesc(bo.getTaskDesc()).taskGroup(bo.getTaskGroup()).taskName(bo.getTaskName())
					.taskRun(bo.getTaskRun()).build();*/
			JobPo jobPo = new JobPo();
			jobPo.setClassName(bo.getClassName());
			jobPo.setCreateTime(new Date());
			jobPo.setTaskCron(bo.getTaskCron());
			jobPo.setTaskDesc(bo.getTaskDesc());
			jobPo.setTaskGroup(bo.getTaskGroup());
			jobPo.setTaskName(bo.getTaskName());
			jobPo.setTaskRun(bo.getTaskRun());
			
			boolean flag = false;
			for (JobPo dBjobPo : selectAll) {
				if (dBjobPo.getClassName().equals(bo.getClassName())) {
					jobPo.setJobId(dBjobPo.getJobId());
					jobDao.update(jobPo);
					flag = true;
				}
			}
			if (flag) {
				continue;
			} else {
				jobDao.save(jobPo);
			}
		}
	}

	@Override
	public InitJobBo getInitJobBoById(String jobIb) {
		JobPo jobPo =  jobDao.findByid( jobIb);
		if (jobPo == null)
			return null;
		InitJobBo bo = new InitJobBo(jobPo.getTaskCron(), jobPo.getTaskName(), jobPo.getClassName(),
				jobPo.getTaskGroup(), jobPo.getTaskDesc(), jobPo.getTaskRun().booleanValue());
		bo.setId(jobPo.getJobId());
		return bo;
	}

}
